package com.ldcc.report_system.ui.setting;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ldcc.report_system.ApplicationConfig;
import com.ldcc.report_system.ReportApplication;
import com.ldcc.report_system.api.results.UpdateAppInfo;
import com.ldcc.report_system.component.VersionUpdateDialog;
import com.ldcc.report_system.databinding.ActivityAboutSoftwareBinding;
import com.ldcc.report_system.ui.MainActivity;
import com.ldcc.report_system.util.ActivitySkipUtil;
import com.ldcc.report_system.util.AlertUtil;
import com.ldcc.report_system.util.ApkVersionUtils;
import com.ldcc.report_system.util.AppInnerDownLoder;
import com.ldcc.report_system.util.ServerUtil;
import com.ldcc.report_system.util.WindowUtils;
import com.ldcc.report_system.util.http.ClientRequestManage;
import com.ldcc.report_system.util.http.HttpObserver;
import com.ldcc.report_system.util.http.ServerResponse;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author wwg
 * @description 个人中心关于软件界面
 * @create 2021-10-21 11:14
 */
public class AboutSoftwareActivity extends AppCompatActivity {

    private static final String TAG = "aboutSoftware";
    private ActivityAboutSoftwareBinding aboutSoftwareBinding;
    private VersionUpdateDialog versionUpdateDialog;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.aboutSoftwareBinding = ActivityAboutSoftwareBinding.inflate(getLayoutInflater());
        setContentView(this.aboutSoftwareBinding.getRoot());
        context = ReportApplication.getContext();
        // 设置界面顶部为透明
        WindowUtils.setWindowTopTransparent(getWindow());
        this.initPage();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                //没有权限则申请权限
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }else {
                //有权限直接执行,docode()不用做处理
                initVersionUpdateDialog();

            }
        }else {
            //小于6.0，不用申请权限，直接执行
            initVersionUpdateDialog();
        }
    }

    /**
     * @description 初始化页面
     */
    private void initPage() {

    }

    /**
     * 初始化更新弹窗
     */
    private void initVersionUpdateDialog() {
        // 检查是否有更新
        aboutSoftwareBinding.aboutSoftwareVersionUpdate.setOnClickListener(view -> {
            String versionName = ApkVersionUtils.getVerName(ReportApplication.getContext());
            int versionCode = ApkVersionUtils.getVersionCode(ReportApplication.getContext());
            Log.e(TAG, "versionName: " + versionName);
            Log.e(TAG, "versionCode: " + versionCode);
            ClientRequestManage.getInstance().getAppVersionApi().checkUpdate(versionCode).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new HttpObserver<UpdateAppInfo>(ReportApplication.getContext(), null) {

                        @Override
                        public void onSuccess(ServerResponse<UpdateAppInfo> response_entity) {
                            UpdateAppInfo updateAppInfo = response_entity.getData();
                            Log.e(TAG, "onSuccess: " + updateAppInfo);
                            if (updateAppInfo == null) {
                                AlertUtil.shortTime("当前已是最新版");
                            }else {
                                String versionName = updateAppInfo.getVersionName();
                                String updateInfo = updateAppInfo.getUpdateInfo();
                                String downUrl = ServerUtil.getServerUrl() + updateAppInfo.getUpdateUrl();
                                String appName = updateAppInfo.getAppName();
                                showVersionUpdateDialog(versionName, updateInfo, downUrl, appName);
                            }
                        }
                    });
        });
    }

    /**
     * @description 返回键事件, 返回, 选择日报界面
     */
    @Override
    public void onBackPressed() {
        ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.USER_INFO_FRAGMENT);
    }

    /**
     * 版本更新弹窗
     * @param versionName 版本名称
     * @param updateInfo 更新内容
     * @param downURL 下载链接
     * @param appName 应用名称
     */
    private void showVersionUpdateDialog(String versionName, String updateInfo, String downURL, String appName) {
        versionUpdateDialog = VersionUpdateDialog
                .with(this)
                .setCancelable(true)
                .setTitle("发现新版本" + versionName)
                .setContent(updateInfo)
                .setPositiveButton("立即更新", view -> {
                    AppInnerDownLoder.downLoadApk(this, downURL, appName);
                })
                .setNegativeButton("暂不更新", view -> {versionUpdateDialog.dismiss();})
                .show();
    }

}